package com.changgou.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author: HuangFu
 * @Date: 2020/2/15 14:21
 * @Description: 微服务Feign请求拦截器
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null){
            //获取HttpServletRequest
            HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();

            if(request != null){
                //获取所有请求头
                Enumeration<String> headerNames = request.getHeaderNames();
                //遍历读取请求头中的JWT，并设置到feign请求中
                while (headerNames.hasMoreElements()){
                    String headerName = headerNames.nextElement();
                    if(headerName.equals("authorization")){
                        requestTemplate.header(headerName,request.getHeader(headerName));
                    }
                }
            }
        }
    }
}
